/*
 * COPYRIGHT Ericpol Telecom sp. z o.o. 2006
 * The copyright to the computer program(s) herein is the property of
 * Ericpol Telecom. The programs may be used and/or copied only with written
 * permission from Ericpol Telecom or in accordance with the terms and
 * conditions stipulated in the agreement under which the
 * programs have been supplied.
 *
 * $Id: StreamRedirector.java 518 2007-05-07 14:59:37Z jacek.kolezynski $
 */
package logmatcher.sipp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Scanner;

import logmatcher.collectors.ServerSocketLogCollector;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
*  Class used to redirect a stream to another stream.
 */
public class StreamRedirector implements Runnable {
	
	/** Class logger. */
    private static final Log LOGGER = LogFactory.getLog(StreamRedirector.class);
	
    //~ Instance fields ------------------------------------------------------------------------------------------------

    /** Reader used for reading data from input stream. */
    private BufferedReader br;

    /** Stream used for writing the data to. */
    private PrintStream ps;

    //~ Constructors ---------------------------------------------------------------------------------------------------

/**
     *  Creates a new StreamRedirector object.
    *
    *  @param inputStream the input stream
    *  @param filename the file name
    */
    public StreamRedirector(InputStream inputStream, String filename) {
        br = new BufferedReader(new InputStreamReader(inputStream));
    	
        File output = new File(filename);

        try {
            ps = new PrintStream(output);
        } catch (FileNotFoundException e) {
        	LOGGER.error("Cannot create file "+filename);
        } 

        new Thread(this).start();
    }

    //~ Methods --------------------------------------------------------------------------------------------------------

    /**
    *  Reads data from input stream and writes it to the output.
    */
    public void run() {

        String line;

        try {
            line = br.readLine();

            while (line != null) {
                if (!line.equals("")) {
                    ps.println(line);
                }

                line = br.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
